import axios from 'axios'
import { baseUrl, ERR_OK, ERR_UNLOGIN } from './config'
import router from 'src/router'
const headUrl = baseUrl + '/api/user'

export const nameCheckApi = (username) => {
  const url = headUrl + '/nameCheck'
  const data = {
    username
  }
  return axios.post(url, data).then((res) => {
    if (res.data.errno === ERR_OK) {
      return Promise.resolve()
    }
    return Promise.reject(res.data.data)
  })
}

export const registerApi = (user) => {
  const url = headUrl + '/register'
  return axios.post(url, user).then((res) => {
    if (res.data.errno === ERR_OK) {
      return Promise.resolve()
    }
    return Promise.reject(res.data.message)
  })
}

export const loginApi = (username, password) => {
  const url = headUrl + '/login'
  const data = {
    username, password
  }
  return axios.post(url, data).then((res) => {
    if (res.data.errno === ERR_OK) {
      return Promise.resolve(res.data.data)
    }
    return Promise.reject(res.data.message)
  })
}

export const getUserApi = () => {
  const url = headUrl + '/getUser'
  return axios.get(url).then((res) => {
    if (res.data.errno === ERR_OK) {
      return Promise.resolve(res.data.data)
    }
    return Promise.reject(res.data.message)
  })
}

export const userLogoutApi = () => {
  const url = headUrl + '/logout'
  return axios.get(url).then((res) => {
    if (res.data.errno === ERR_OK) {
      return Promise.resolve(res.data)
    }
    return Promise.reject(res.data.message)
  })
}

axios.interceptors.response.use(async (response) => {
  if (response.data.errno === ERR_UNLOGIN) {
    await router.replace({
      path: '/login'
    })
  }
  return response
})
